package tcp_server_demo

import (
	"fmt"
	"net"
)

type Server struct {
	*connMsg
}

func (s *Server) Start(network string, addr string) error {
	listener, err := net.Listen(network, addr)
	if err != nil {
		return err
	}
	defer listener.Close()
	for {
		var conn net.Conn
		conn, err = listener.Accept()
		if err != nil {
			return err
		}
		var req []byte
		req, err = s.Read(conn)
		if err != nil {
			return err
		}
		res := s.handleService(req)
		err = s.Write(conn, res)
		if err != nil {
			return err
		}
	}
}

func (s *Server) handleService(req any) []byte {
	return []byte(fmt.Sprintf("%s + 1", req))
}

func NewServer() *Server {
	return &Server{}
}
